<?php
require_once 'vendor/autoload.php';

/**
 * 消息推送驱动器组件：Eml.CIEmail[消息子模型-EML.CIEmail!]
 * 
 * @date	2017年7月20日 下午6:42:57
 * 
 */
class MessagePusherEml_CIEmail extends CI_Driver implements libraries\common\MessagePusherInterface
{
	const DEBUG_MODE = false;
	/** @var CI_Controller */
	private $CI       = null;
	/** @var CI_Email */
	private $CIEmail       = null;
// 	'protocol' => 'smtp',
// 	'smtp_host' => 'smtp.qq.com',
// 	'smtp_user' => 'WangERuYan@qq.com',
// 	'smtp_pass' => 'CAIChengXuZu',
// 	'smtp_port' => 465,
// 	'smtp_timeout' => 5,
// 	'smtp_keepalive' => TRUE,
// 	'smtp_crypto' => 'ssl',
// 	'mailtype' => 'html',
// 	'charset' => 'UTF-8',
	
	private $lastResponse       = null;
	
	public function __set($var, $val)
	{
		$this->CIEmail->initialize([$var => $val]);
		// Handle mailFromName
		// MARK CI_Email 禁止了外来注入，所以对于配置中自定义的变量，需要设置到本对象，而不是 $this->email 中。
		# if (isset($this->$key))
		# {
		# 	$this->$key = $val;
		# }
		$this->$var = $val;
	}
	
	public function __construct($config = array())
	{
		$this->CI =& get_instance();
		
		$this->CI->load->library('email');
		$this->CIEmail =& $this->CI->email;
	}
	
	/**
	 * 给定数据执行推送
	 *
	 * @param array $data
	 *
	 * @return void
	 */
	public function pushPerform($data)
	{
		if(self::DEBUG_MODE) {
			return ;
		}
		$toEmail = $data['email'];
		$subject = $data['subject'];
		$message = $data['msg'];
		$this->lastResponse = $this->send($toEmail, $subject, $message);
	}
	
	/**
	 * 获取上一次推送的状态
	 *
	 * @return boolean
	 */
	public function getStatus()
	{
		if(self::DEBUG_MODE) {
			return true;
		}
		$response = $this->getParsedResponse();
		if($response == true) {
			return true;
		}
		
		return false;
	}
	
	public function getMessage()
	{
		$response = $this->getParsedResponse();
		if($response) {
			return 'success';
		}
		// 返回一个包含了所有的服务器信息、Email 头部信息、以及 Email 正文信息的字符串。用于调试。
		$debuger = $this->CIEmail->print_debugger();
		// 你可以指定只返回消息的哪个部分，有效值有：headers 、 subject 和 body 。
		$headers = $this->CIEmail->print_debugger(['headers']);
		$subject = $this->CIEmail->print_debugger(['subject']);
		$body = $this->CIEmail->print_debugger(['body']);
		
		return $debuger;
	}
	
	public function send($toMail, $subject, $message)
	{
		$body = $message;
		$from = $this->CIEmail->smtp_user;
		// Handle mailFromName
		#$name = $this->CIEmail->mailFromName;
		$name = $this->mailFromName;
		$return = $from;
		$this->CIEmail->from($from, $name, $return);
		$this->CIEmail->to($toMail);
		$this->CIEmail->subject($subject);
		$this->CIEmail->message($body);
		// $this->CIEmail->attach('application\controllers\1.jpeg'); //相对于index.php的路径
		$result = false;
		try {
			/*
			<h4>A PHP Error was encountered</h4>
			<p>Severity: Warning</p>
			<p>Message:  fsockopen(): unable to connect to ssl://smtp.126.com:465 (Connection timed out)</p>
			<p>Filename: libraries/Email.php</p>
			<p>Line Number: 2063</p>
			 */
			// php error 捕获
			// 在实际开发中，错误及异常捕捉仅仅靠try{}catch()是远远不够的。
			// See To: http://blog.csdn.net/e421083458/article/details/8157154
			$result = $this->CIEmail->send();
		} catch (ErrorException $e) {
			// not catched!
			var_dump($e);
		} catch (Exception $e) {
			// not catched!
			var_dump($e);
		}
		
		return $result;
	}
	
	private function getParsedResponse()
	{
		if(!isset($this->lastResponse)) {
			trigger_error(sprintf("%s::%s: You Shouldn't call me here, because no response now!", __CLASS__, __METHOD__), E_USER_ERROR);
			return false;
		}
		
		$response = $this->lastResponse;
		
		//print_r($response);
		return $response;
	}
	
}

